﻿using System;
using System.Security.Principal;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication2
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class RequiresAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            IPrincipal user = filterContext.HttpContext.User;
            if (!user.Identity.IsAuthenticated)
            {
                var langRoute = string.Empty;
                if(filterContext.RouteData.Values.ContainsKey("lang"))
                {
                    langRoute = filterContext.RouteData.Values["lang"] as string;

                    langRoute += "/";
                }

                filterContext.Result = new RedirectResult(langRoute + "/Account/Login");
            }
        }
    }
    public class AuthorizeEx : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                var returnUrl = System.Web.Security.FormsAuthentication.LoginUrl + "?returnUrl=" +
                                filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl);

                filterContext.Result = new RedirectResult(returnUrl);

                //var actionName = actionDescriptor.ActionName;
                //var controllerName = actionDescriptor.ControllerDescriptor.ControllerName;

                //filterContext.Result =
                //    new RedirectToRouteResult(new RouteValueDictionary
                //                                          {
                //                                              {"controller", controllerName},
                //                                              {"action", actionName},
                //                                          });

            }
        }
    }
}
